import { fillInputDone, isFillYearBeforeLast } from '../../common.js';
import { CWBB_JSON, CWBB_JSON_MONTH } from '../data/cwbbData.js';
export function fillCwbb({ saasData, baseInfo }, sheet) {
  console.log(saasData);
  let isYearReport = saasData.isYearReport;
  if (!isYearReport) { // 月季报
    try {
      fillMonthCwbb(saasData, baseInfo)
      fillInputDone({
        tax: 'cwbb', // 税种
        success: true, // 是否成功
        message: '财务报表-填报成功' // 文案
      });
    } catch (e) {
      console.error(e);
      fillInputDone({
        tax: 'cwbb', // 税种
        success: false, // 是否成功
        message: '财务报表-填报失败，请联系技术人员' // 文案
      });
    }

    return true;
  }
  // 年报
  // const isYearReport = saasData.isYearReport;
  const companyInfo = JSON.parse(window.localStorage.getItem('companyInfo'));
  const IsFillYearBeforeLast = isFillYearBeforeLast(companyInfo);
  console.log(IsFillYearBeforeLast);
  const ins = saasData.data.openParams.taxInfo.institution === '2013'
    ? 'xqykjzz'
    : 'qykjzz';
  let inputData;
  inputData = saasData.data.openParams.inputData.data[sheet];
  let lastYearData = saasData.data.openParams.inputData.lastYearData[sheet];
  if (
    IsFillYearBeforeLast
    && ins === 'xqykjzz'
    && (sheet === 'profit' || sheet === 'cash')
  ) {
    inputData = inputData.map((item, index) => {
      let obj = Object.assign(item);
      obj.colValue1 = item.colValue1;
      obj.colValue2 = lastYearData[index].colValue1;
      obj.reportItemName = lastYearData[index].reportItemName;
      return obj;
    });
  } else if (
    IsFillYearBeforeLast
    && ins === 'qykjzz'
    && (sheet === 'profit' || sheet === 'cash')
  ) {
    inputData = inputData.map((item, index) => {
      let obj = Object.assign(item);
      obj.colValue1 = item.colValue3;
      obj.colValue2 = lastYearData[index].colValue3;
      obj.reportItemName = lastYearData[index].reportItemName;
      return obj;
    });
  } else if (
    !IsFillYearBeforeLast
    && ins === 'qykjzz'
    && (sheet === 'profit' || sheet === 'cash')
  ) {
    inputData = inputData.map((item) => {
      let obj = Object.assign(item);
      obj.colValue1 = item.colValue3;
      obj.colValue2 = '0.00';
      return obj;
    });
  } else if (
    !IsFillYearBeforeLast
    && ins === 'xqykjzz'
    && (sheet === 'profit' || sheet === 'cash')
  ) {
    inputData = inputData.map((item) => {
      let obj = Object.assign(item);
      obj.colValue1 = item.colValue1;
      obj.colValue2 = '0.00';
      return obj;
    });
  }
  // 小企业会计准则填报
  if (ins === 'xqykjzz') {
    try {
      inputData = inputData.filter((item) => {
        return item.reportItemRowNbr && parseInt(item.reportItemRowNbr);
      });
      inputData = inputData.sort(
        (a, b) => a.reportItemRowNbr - 0 - (b.reportItemRowNbr - 0)
      );
      switch (sheet) {
        case 'balance':
          const balanceNoNeedFillInput = [15, 29, 30, 41, 46, 47, 52, 53];
          fillData(
            ['#001C', '#001D', '#001G', '#001H'],
            inputData,
            balanceNoNeedFillInput,
            30
          );
          break;
        case 'profit':
          const profitNoNeedFillInput = [21, 30, 32];
          fillData(['#004G', '#004J'], inputData, profitNoNeedFillInput);
          break;
        case 'cash':
          const cashNoNeedFillInput = [7, 13, 19, 20, 22];
          fillData(['#005E', '#005F'], inputData, cashNoNeedFillInput);
          break;
        default:
          break;
      }
      fillInputDone({
        tax: 'cwbb', // 税种
        success: true, // 是否成功
        message: '财务报表-填报成功' // 文案
      });
    } catch (e) {
      console.log(e);
      fillInputDone({
        tax: 'cwbb', // 税种
        success: false, // 是否成功
        message: '财务报表-填报失败，请联系技术人员' // 文案
      });
    }
  } else {
    // 企业会计准则填报
    try {
      fillQykjzzData(inputData, sheet);
      fillInputDone({
        tax: 'cwbb', // 税种
        success: true, // 是否成功
        message: '财务报表-填报成功' // 文案
      });
    } catch (e) {
      console.log(e);
      fillInputDone({
        tax: 'cwbb', // 税种
        success: false, // 是否成功
        message: '财务报表-填报失败，请联系技术人员' // 文案
      });
    }
  }
}

function fillMonthCwbb(saasData, baseInfo) {
  const sheet = saasData.sheet;
  const ins = baseInfo.companyInfo.institutionCode === '2' ? 'xqykjzz' : 'qykjzz';
  if (ins !== 'xqykjzz') throw new Error('未支持的会计准则');
  const inputData = saasData.data.openParams.inputData.data[sheet];
  const vk = CWBB_JSON_MONTH[ins][sheet];
  // const obj = {};
  for (let k in vk) {
    let input = $(`#${k}`);
    if (!input.attr('disabled')) {
      let v = vk[k];
      v = v.replace('h', '');
      let saasItem = inputData[v];
      // 资产负债表期初余额  利润表不需要填本年累计
      if (sheet !== 'profit' && (k.includes('C') || k.includes('G'))) {
        // obj[k] = saasItem.colValue1;
        input.val(saasItem.colValue1).blur();
      }
      // 资产负债期末余额  利润表本期金额
      if (k.includes('D') || k.includes('H') || k.includes('J')) {
        // obj[k] = saasItem.colValue2;
        input.val(saasItem.colValue2).blur();
      }
    }

  }

}

// 小企业会计准则填表方法
function fillData(id, inputData, noNeedFillInput, isSwitch = Infinity) {
  inputData.forEach((item) => {
    item.reportItemRowNbr -= 0;
    let qmyeId = '';
    let ncyeId = '';
    if (noNeedFillInput.indexOf(item.reportItemRowNbr - 0) === -1) {
      if (isSwitch && item.reportItemRowNbr <= isSwitch) {
        qmyeId = `${id[0]}${item.reportItemRowNbr}`;
        ncyeId = `${id[1]}${item.reportItemRowNbr}`;
        // 后面的选择表给资产负债表后面部分做配对
      } else if (
        item.reportItemRowNbr > isSwitch
        && item.reportItemRowNbr < isSwitch + 12
      ) {
        qmyeId = `${id[2]}${item.reportItemRowNbr - isSwitch}`;
        ncyeId = `${id[3]}${item.reportItemRowNbr - isSwitch}`;
      } else if (
        item.reportItemRowNbr >= isSwitch + 12
        && item.reportItemRowNbr <= isSwitch + 14
      ) {
        qmyeId = `${id[2]}${item.reportItemRowNbr - isSwitch + 1}`;
        ncyeId = `${id[3]}${item.reportItemRowNbr - isSwitch + 1}`;
      } else if (
        item.reportItemRowNbr >= isSwitch + 15
        && item.reportItemRowNbr < isSwitch + 16
      ) {
        qmyeId = `${id[2]}${item.reportItemRowNbr}`;
        ncyeId = `${id[3]}${item.reportItemRowNbr}`;
      } else {
        qmyeId = `${id[2]}${item.reportItemRowNbr - 23}`;
        ncyeId = `${id[3]}${item.reportItemRowNbr - 23}`;
      }
      $(qmyeId).val(item.colValue1).blur();
      $(ncyeId).val(item.colValue2).blur();
    }
  });
}

// 企业会计准则填表方法(根据映射表对税局表格填值)
function fillQykjzzData(inputData, sheet) {
  switch (sheet) {
    case 'balance':
      const tempData = transformData(inputData, CWBB_JSON.balance[2007]);
      Object.keys(tempData).forEach((item) => {
        $(item).val(tempData[item]).blur();
      });
      console.log(tempData);
      break;
    case 'profit':
      const tempData2 = transformData(inputData, CWBB_JSON.profit[2007]);
      Object.keys(tempData2).forEach((item) => {
        $(item).val(tempData2[item]).blur();
      });
      console.log(tempData2);
      break;
    case 'cash':
      dealData(inputData);
      break;
    default:
      break;
  }
}

function transformData(inputData, transformJson) {
  let result = {};
  for (let key in transformJson) {
    const item = inputData.find(
      (obj) => obj.reportItemUuid === transformJson[key].uuid
    );
    if (item) {
      result[key] = item[transformJson[key].value]
        ? Number(item[transformJson[key].value])
        : 0;
    }
  }
  return result;
}

function dealData(inputData) {
  const tempItem = inputData.find((a) => a.reportItemUuid === 'P3$36');
  console.log(tempItem);
  const tempArr = inputData.filter((item) => item.reportItemType === 'DATA');
  tempArr.splice(31, 0, tempItem);
  console.log(tempArr.length);
  const obj = {};
  const obj1 = {};
  for (let i = 5; i <= 41; i++) {
    if (i === 15 || i === 28) {
      // eslint-disable-next-line no-continue
      continue;
    }
    const str1 = `#006_${i}_5`;
    obj[str1] = '';
  }
  for (let i = 5; i <= 41; i++) {
    if (i === 15 || i === 28) {
      // eslint-disable-next-line no-continue
      continue;
    }
    const str2 = `#006_${i}_6`;
    obj1[str2] = '';
  }
  console.log(Object.keys(obj).length);
  const jumpCol = [3, 8, 9, 15, 20, 21, 25, 29, 30, 32, 344];
  Object.keys(obj).forEach((ele, i) => {
    if (jumpCol.indexOf(i) === -1) {
      $(ele).val(tempArr[i].colValue1).blur();
    }
  });
  Object.keys(obj1).forEach((ele, i) => {
    if (jumpCol.indexOf(i) === -1) {
      $(ele).val(tempArr[i].colValue2).blur();
    }
  });
}


export function btnclickEvent() {
  let timer = setInterval(() => {
    const tr = document.querySelector('.mini-tabs-headers tr');
    if (tr) {
      const tds = tr.querySelectorAll('td');
      const balance = Array.from(tds).find((td) => $(td).text().search('资产负债表') > -1);
      if (balance) {
        console.log(tr);
        getPeriodAndType('balance', '资产负债表');
        tr.addEventListener('click', function (e) {
          // 给左侧菜单栏绑定事件
          e.preventDefault();
          let type = 'balance';
          let typeText = '资产负债表'
          if (
            e.target
            && $(e.target)
              .text()
              .search('资产负债表') > -1
          ) {
            type = 'balance';
            typeText = '资产负债表'
          } else if (
            e.target
            && $(e.target)
              .text()
              .search('现金流量表') > -1
          ) {
            type = 'cash';
            typeText = '现金流量表'
          } else if (
            e.target
            && $(e.target)
              .text()
              .search('利润表') > -1
          ) {
            type = 'profit';
            typeText = '利润表'
          }
          console.log(type);
          getPeriodAndType(type, typeText);
        });
        clearInterval(timer);
        timer = null;
      }
    }
  }, 3000);
}

function getPeriodAndType(type, typeText) {
  try {
    const startTime = $(`table[sb_title=${typeText}] .sssqq`).text().trim().slice(0, 7);
    const endTime = $(`table[sb_title=${typeText}] .sssqz`).text().slice(0, 7);
    // debugger
    window.postMessage(
      {
        event: 'setPeriodAndType',
        data: {
          type: type,
          startTime: startTime,
          endTime: endTime
        }
      },
      '*'
    );
  } catch (e) {
    console.log(e);
    window.postMessage({
      event: 'setPeriodAndType',
      data: {
        type: type,
        startTime: '',
        endTime: ''
      }
    })
  }

}